import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { getVerifyCode, requestLogin } from '@/service/module/login'
import { localCache } from '@/utils/cache'
import { CacheType } from '@/global/constant'

interface IToken {
  tokenName: string
  tokenValue: string
}

interface ILoginState {
  code: string
  token: IToken
}

/* 数据区 */
const initialState: ILoginState = {
  // 登录的图片验证码
  code: '',
  // 公钥
  // 用户唯一标识
  token: {
    tokenName: '',
    tokenValue: ''
  }
}

/** 异步action **/
// 获取图片验证码
export const fetchVerifyCodeAction = createAsyncThunk(
  'fetch/verifyCode',
  async (_, { dispatch }) => {
    const res = await getVerifyCode()
    dispatch(changeImgVerifyCodeAction(res.data))
  }
)

// 登录
export const fetchLoginAction = createAsyncThunk<any, string>(
  'fetch/login',
  async (loginParams, { dispatch }) => {
    const res = await requestLogin(loginParams)
    // 2.请求成功保存token
    const { tokenName, tokenValue } = res.data
    const token = { tokenName, tokenValue }
    localCache.setCache(CacheType.TOKEN, token)
    dispatch(changeTokenAction(token))
    return '登录action成功'
  }
)

const loginSlice = createSlice({
  name: 'login',
  initialState,
  reducers: {
    // 保存登录验证码
    changeImgVerifyCodeAction(state, { payload }) {
      state.code = payload
    },
    // 保存token
    changeTokenAction(state, { payload }) {
      state.token = payload
    }
  }
})

export const { changeImgVerifyCodeAction, changeTokenAction } =
  loginSlice.actions
export default loginSlice.reducer
